import { Button, Form, Input, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'

import { CONST_ROUTES } from '@/constants'
import { useMainStore } from '@/store'

export default function LoginPage() {
  const navigate = useNavigate()
  const { login } = useMainStore()

  async function handleLogin(data: Record<string, any>) {
    const loading = Toast.show({
      icon: 'loading',
      content: '加载中',
      duration: 0
    })

    try {
      await login(data)
      navigate(CONST_ROUTES.INDEX, { replace: true })
    } finally {
      loading.close()
    }
  }

  return (
    <div>
      <Form
        layout="horizontal"
        hasFeedback={false}
        onFinish={values => {
          handleLogin(values)
        }}
        onFinishFailed={errorInfo => {
          const error = errorInfo.errorFields[0].errors[0]

          Toast.show({
            icon: 'fail',
            content: error
          })
        }}
        footer={
          <Button
            type="submit"
            color="primary"
            size="large"
            style={{
              width: '100%'
            }}
          >
            登录
          </Button>
        }
      >
        <Form.Item
          name={'username'}
          label="账号"
          rules={[{ required: true, message: '请输入账号' }]}
        >
          <Input placeholder="请输入账号"></Input>
        </Form.Item>
        <Form.Item
          name={'password'}
          label="密码"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input type="password" placeholder="请输入密码"></Input>
        </Form.Item>
      </Form>
    </div>
  )
}
